package cn.actoncode.boot.module.ai.service.intelligentagent;

import cn.actoncode.boot.framework.web.core.util.WebFrameworkUtils;
import cn.actoncode.boot.module.ai.controller.app.intelligentagent.vo.IntelligentAgentChatReqVO;
import cn.actoncode.boot.module.ai.controller.app.intelligentagent.vo.IntelligentAgentChatRespVO;
import cn.actoncode.boot.module.ai.controller.app.intelligentagent.vo.IntelligentAgentUsedAbilityReqVO;
import cn.actoncode.boot.module.ai.controller.app.intelligentagent.vo.IntelligentAgentUsedAbilityRespVO;
import cn.actoncode.boot.module.ai.dal.dataobject.ability.AbilityDO;
import cn.actoncode.boot.module.ai.dal.dataobject.chat.ChatRecordDO;
import cn.actoncode.boot.module.ai.dal.dataobject.intelligentagent.IntelligentAgentDO;
import cn.actoncode.boot.module.ai.dal.mapper.intelligentagent.IntelligentAgentMapper;
import cn.actoncode.boot.module.ai.service.ability.AbilityService;
import cn.actoncode.boot.module.ai.service.ability.AbilityUsedRecordService;
import cn.actoncode.boot.module.ai.service.chat.ChatRecordService;
import cn.actoncode.boot.module.ai.service.chatmodel.ChatStrategyContext;
import cn.actoncode.boot.module.ai.service.chatmodel.ChatStrategyService;
import cn.actoncode.boot.module.ai.service.chatmodel.dto.ChatHistoryDTO;
import cn.actoncode.boot.module.ai.service.chatmodel.dto.ChatRespDTO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 智能体 Service 实现类
 *
 * @author bin
 */
@Service
@Valid
@Slf4j
public class IntelligentAgentServiceImpl implements IntelligentAgentService {

    private final String engine = "ChatGLM4"; //TODO 可做成配置项

    @Resource
    private IntelligentAgentMapper intelligentAgentMapper;

    @Resource
    private ChatStrategyContext chatStrategyContext;

    @Resource
    private ChatRecordService chatRecordService;

    @Resource
    private AbilityService abilityService;

    @Resource
    private AbilityUsedRecordService abilityUsedRecordService;

    @Override
    public IntelligentAgentChatRespVO chat(IntelligentAgentChatReqVO reqVO) {
        // 获取智能体
        IntelligentAgentDO intelligentAgent = intelligentAgentMapper.selectById(reqVO.getIntelligentAgentId());
        // 获取对用引擎
        ChatStrategyService service = chatStrategyContext.getResource(engine);
        // 构建历史数据
        List<ChatHistoryDTO> historyList = buildHistory();
        // 聊天
        ChatRespDTO chat = service.chat(reqVO.getPrompt(), historyList,
                intelligentAgent.getSetting(), true, null, reqVO.getSk());
        Long userId = WebFrameworkUtils.getLoginUserId();
        // 记录聊天
        chatRecordService.insertChatRecord(userId, reqVO.getIntelligentAgentId(), reqVO.getPrompt(), chat.getText());
        // 返回
        return IntelligentAgentChatRespVO.builder().prompt(reqVO.getPrompt()).text(chat.getText()).build();
    }

    @Override
    public IntelligentAgentUsedAbilityRespVO usedAbility(IntelligentAgentUsedAbilityReqVO reqVO) {
        // 获取能力
        AbilityDO ability = abilityService.getAbility(reqVO.getAbilityId());
        // 获取对用引擎
        ChatStrategyService service = chatStrategyContext.getResource(engine);
        String prompt = ability.getPrompt().formatted(reqVO.getPrompt());
        // 聊天
        ChatRespDTO chat = service.chat(prompt, new ArrayList<>(),
                ability.getSetting(), true, null, reqVO.getSk());
        Long userId = WebFrameworkUtils.getLoginUserId();
        // 新增能力使用记录
        Long recordId = abilityUsedRecordService.insertAbilityUsedRecord(userId, reqVO.getAbilityId(),
                reqVO.getIntelligentAgentId(), ability.getType(), reqVO.getPrompt(), chat.getText());
        // 返回
        return IntelligentAgentUsedAbilityRespVO.builder().prompt(reqVO.getPrompt())
                .text(chat.getText()).recordId(recordId).build();
    }

    public List<ChatHistoryDTO> buildHistory() {
        Long userId = WebFrameworkUtils.getLoginUserId();
        List<ChatRecordDO> chatRecordList = chatRecordService.getChatRecordList(userId);
        List<ChatHistoryDTO> historyList = new ArrayList<>();
        chatRecordList.forEach(record -> {
            ChatHistoryDTO historyDTO = new ChatHistoryDTO();
            historyDTO.setQuery(record.getPrompt());
            historyDTO.setContent(record.getText());
        });
        return historyList;
    }

    @Override
    public IntelligentAgentDO getIntelligentAgent() {
        return intelligentAgentMapper.getIntelligentAgent();
    }


}
